package com.iwayin.core.dao.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.iwayin.core.dao.BaseDAOImpl;
import com.iwayin.core.dataobject.UserDO;
import com.iwayin.core.utils.StringUtil;
import com.iwayin.core.vo.SearchVO;

public class UserDAOImpl extends BaseDAOImpl implements UserDAO {
	//内置本机缓存
	private LoadingCache<String, UserDO> emailReceiverCache = CacheBuilder.newBuilder()
			.expireAfterAccess(3600*24, TimeUnit.SECONDS).maximumSize(10000)
			.build(new CacheLoader<String, UserDO>(){
				@Override
				public UserDO load(String key) throws Exception {
					logger.debug("Read User From DB====================");
					String[] strs = key.split(":");
					UserDO user =  (UserDO) queryForObject("UserDAO.getEmailReceiver", Long.valueOf(strs[1]));
					if(user == null)
						user = new UserDO();
					return user;
				}
			});
	
	private void removeEmailReceiver(Long userId) {
		emailReceiverCache.invalidate("RECEIVER:" + userId.toString());
	}
	@Override
	public UserDO getEmailReceiver(Long userId) {
		UserDO user = get(userId);
		if(user != null && StringUtil.isEmpty(user.getLoginName())){
			removeEmailReceiver(userId);
			return null;
		}
		return user;
	}
	
	private UserDO get(Long userId) {
		try {
			return emailReceiverCache.get("RECEIVER:" + userId.toString());
		} catch (ExecutionException e) {
			return null;
		}
	}

	@Override
	public Long addUser(UserDO user) {
		return (Long) executeInsert("UserDAO.addUser", user);
	}

	@Override
	public UserDO getUserById(Long userId) {
		return (UserDO) queryForObject("UserDAO.getUserById", userId);
	}

	@Override
	public UserDO getUserByLoginName(String loginName) {
		return (UserDO) queryForObject("UserDAO.getUserByLoginName", loginName);
	}
	
	@Override
	public UserDO getUserByNickName(String nickname) {
		return (UserDO) queryForObject("UserDAO.getUserByNickName", nickname);
	}

	@Override
	public Integer updatePassword(UserDO user) {
		return this.getSqlMapClientTemplate().update("UserDAO.updatePassword", user);
	}

	@Override
	public UserDO getUserByEmail(String email) {
		return (UserDO) queryForObject("UserDAO.getUserByEmail", email);
	}

	@Override
	public void fansCountPlusOne(Long userId) {
		this.getSqlMapClientTemplate().update("UserDAO.fansCountPlusOne", userId);
	}

	@Override
	public void fansCountMinusOne(Long userId) {
		this.getSqlMapClientTemplate().update("UserDAO.fansCountMinusOne", userId);
	}

	@Override
	public void followCountPlusOne(Long userId) {
		this.getSqlMapClientTemplate().update("UserDAO.followCountPlusOne", userId);
	}

	@Override
	public void followCountMinusOne(Long userId) {
		this.getSqlMapClientTemplate().update("UserDAO.followCountMinusOne", userId);
	}

	@Override
	public void updateUserInfo(UserDO user) {
		this.getSqlMapClientTemplate().update("UserDAO.updateUserInfo", user);
		//清楚缓存
		removeEmailReceiver(user.getId());
	}

	@Override
	public void askCountPlusOne(Long userId) {
		this.getSqlMapClientTemplate().update("UserDAO.askCountPlusOne",userId);
	}
	
	@Override
	public void askCountminuOne(Long userId) {
		executeUpdate("UserDAO.askCountminuOne", userId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserDO> listUser(UserDO query) {
		return executeQueryForList("UserDAO.listUser", "UserDAO.listUser.count", query);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<SearchVO> searchUser(SearchVO query) {
		return this.executeQueryForList("UserDAO.searchUser", "UserDAO.searchUser.count",query);
	}
	@Override
	public List<UserDO> findUsers(List<Long> userIds) {
			if(userIds ==null){
				return new ArrayList<UserDO>();
			}
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("userIds", userIds);
			return this.queryForList("UserDAO.findUsers", params);
		}
	@Override
	public void answerCountPlusOne(Long userId) {
		this.getSqlMapClientTemplate().update("UserDAO.answerCountPlusOne",userId);
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Long> findSystemUsers() {
		return this.getSqlMapClientTemplate().queryForList("UserDAO.findSystemUsers");
	}

	@Override
	public void likeReceivePlusOne(Long userId) {
		executeUpdate("UserDAO.likeReceivePlusOne", userId);
	}
	@Override
	public void updateUserStatus(UserDO user) {
		executeUpdate("UserDAO.updateUserStatus", user);
	}
	@Override
	public void likeReceiveMinusOne(Long userId) {
		executeUpdate("UserDAO.likeReceiveMinusOne", userId);
	}

	@Override
	public List<UserDO> findCanSendEmail() {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("status", 1);
		return queryForList("UserDAO.findCanSendEmail", params);
	}
	
}
	


	
